<?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 Juliet George on Medium]]></title>
        <description><![CDATA[Stories by Juliet George on Medium]]></description>
        <link>https://medium.com/@georgejuliet11?source=rss-bd9ddba54cd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cG5IQK0L05c330_KXSMwuw@2x.jpeg</url>
            <title>Stories by Juliet George on Medium</title>
            <link>https://medium.com/@georgejuliet11?source=rss-bd9ddba54cd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:23:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@georgejuliet11/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[Dynamic Programming: The Knapsack Problem]]></title>
            <link>https://georgejuliet11.medium.com/dynamic-programming-the-knapsack-problem-ccc7c2df36ad?source=rss-bd9ddba54cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccc7c2df36ad</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[knapsack-problem]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <dc:creator><![CDATA[Juliet George]]></dc:creator>
            <pubDate>Wed, 17 Apr 2024 19:05:50 GMT</pubDate>
            <atom:updated>2025-05-10T21:37:52.360Z</atom:updated>
            <content:encoded><![CDATA[<p>In the third part of my dynamic programming series, I will solve the Knapsack Problem.</p><p>The problem is as follows:</p><blockquote><strong>Given a knapsack with a maximum capacity of W and a list of items, select the items that fit inside the knapsack and yield the highest value.</strong></blockquote><h3>Optimal Substructure and Recurrence Equation</h3><p>Dynamic programming solves a hard problem by solving subproblems and combining the results. When a problem can be solved using dynamic programming, it is said to have an optimal substructure.</p><p>Let’s assume you win a one-time shopping experience with <strong>Jeff Bezos</strong> and are given a knapsack that can hold <strong>5 lbs</strong>. If you have to choose between these three items:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*QPDRT9rd1ZrG4BOXAYvzxg.jpeg" /><figcaption>Coffee machine — $5000– 5lbs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dH3BkSM5lyGR8PjAd6gt_w.jpeg" /><figcaption>Macbook — $4000–3lbs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*h-pXVmPEfggaJtHFgrUDhQ.jpeg" /><figcaption>Rolex watch — $10,000–2lbs</figcaption></figure><p>What items would you add to your knapsack to get the maximum value?</p><p>For an item<strong> </strong>with weight Wj and value Vj, you can either take it or leave it. If you choose to take it, the new capacity of your knapsack is <strong>5 — Wj, </strong>and<strong> </strong>the value of your knapsack increases by Vj.</p><p>The recurrence equation is the maximum between taking or leaving the current item:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*yKzdFOMSJS9F6-hwXfx1QQ.png" /><figcaption>The recurrence equation</figcaption></figure><p>Using the equation above, you can solve the problem with the following steps:</p><ol><li>Determine the base cases: a) when the knapsack capacity is zero, the maxValue is zero. b) When the knapsack is over capacity, the value is negative infinity(a value that is not useful).</li><li>Call solve the recurrence equation.</li></ol><pre>def maxValue(W, j, weights, values):<br>    if W == 0: # basecase 1: no knapsack at all<br>        return 0<br>    if W &lt; 0: # basecase 2: knapsack is out of capacity<br>        return -float(&#39;inf&#39;)<br>    if j &gt;= len(weights): # the current item is not in the weights list<br>        return 0<br>    return max(values[j] + maxValue(W-weights[j], j+1, weights, values), maxValue(W, j+1, weights, values))<br>  </pre><h3>Memoize</h3><p>You can optimize the <strong>maxValue</strong> function by storing and reusing previously calculated values in a two-dimensional table. Let’s create a table: the rows will be the items, and the columns have the knapsack capacity from 1lb to 5lb.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*4RayR0Eq8YxzrmCpHtiBqA.png" /></figure><p>Starting from the coffee table row, you will fill the grid row by row until the final result.</p><h4>Rolex row, 2lbs</h4><p>The Rolex is the first item and therefore the only item to consider at this stage. It weighs 2lb and can fit in the 2lb, 3lb, 4lb, and 5lb knapsacks. Let’s add the value of the Rolex in the corresponding knapsack columns of the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*q7q5bR2hO55bTMSy9Xselg.png" /></figure><p><strong>The MacBook row, 3lbs</strong></p><p>For the second row, you can pick the Rolex or the MacBook. The Macbook and Rolex won&#39;t fit into the 1lb knapsack. The MacBook is too heavy for the 2lb knapsack but the Rolex can fit, so you take the Rolex. The Macbook fits into the 3lb and 4lb knapsack but since the goal of the exercise is to maximize the value, you pick the Rolex in both columns. The 5lb knapsack can fit both the Rolex and MacBook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*h0MY2JdUGGBqUIrTWFeo0g.png" /></figure><h4>The coffee maker row</h4><p>In the third row, you can add the Rolex, the MacBook, or/and the Coffee maker. The 1lb knapsack can’t fit any of the items. The 2lb knapsack can fit the Rolex. The 3lb and 4lb knapsacks can fit the Rolex or the MacBook, but the Rolex has the highest value so you pick the Rolex. The 5lb knapsack can fit the Rolex and MacBook or only the coffee maker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*TP6NxzxZMF7Os4ZP75mjUA.png" /></figure><h4>Writing the Code</h4><p>The solution to the optimized version of maxValue is as follows:</p><ol><li>Fill a 2D list with zeros and pass it to a variable, T. This will store the maxValue for each knapsack.</li><li>Fill another 2D list, S. For every cell, store 1 if you take the item in that cell and store 0 if you leave that item. That is, if the item is taken S[(knapsack, item)] = 1, else S[(knapsack, item) = 0.</li><li>Create a helper function to retrieve previously calculated maxValue from T.</li><li>Run two for-loops to fill T and S.</li><li>Retrieve the items to pick.</li></ol><pre>def memoizedMaxValue(W, weights, values):<br>    n = len(weights)<br>    if W == 0:<br>        return 0<br>    T = [[0 for j in range(n) ]for w in range(W+1)]<br>    S = [[0 for j in range(n) ]for w in range(W+1)]<br>    <br>    def retrieveTableEntry(i,j):<br>        if i == 0:<br>            return 0<br>        if i &lt; 0:<br>            return -float(&#39;inf&#39;)<br>        return T[i][j]<br>  <br>    for i in range(1, W+1):<br>        for j in range(n-1, -1, -1):<br>            T[i][j], S[i][j] = max((values[j] + retrieveTableEntry(W-weights[j], j+1),1), (retrieveTableEntry(W-weights[j], j+1),0))<br>    <br>    itemsToPick = []<br>    weight = W<br>    for j in range(n):<br>        if S[weight][j] == 1:<br>            itemsToPick.append(j)<br>            weight = weight - weights[j]<br>     return T[W][0], itemsToPick</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccc7c2df36ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sorting Algorithms: Bubble Sort, Merge Sort, and Quick sort]]></title>
            <link>https://georgejuliet11.medium.com/sorting-algorithms-bubble-sort-merge-sort-and-quick-sort-0afcf9f892ae?source=rss-bd9ddba54cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/0afcf9f892ae</guid>
            <dc:creator><![CDATA[Juliet George]]></dc:creator>
            <pubDate>Thu, 14 Mar 2024 22:29:01 GMT</pubDate>
            <atom:updated>2024-09-25T01:07:13.235Z</atom:updated>
            <content:encoded><![CDATA[<p>This tutorial is designed for those familiar with Python and basic coding concepts, including time complexity. It provides a clear and concise overview of bubble sort, merge sort, and quick sort.</p><p><strong>Bubble Sort</strong></p><p>The bubble sort algorithm is a basic and easy-to-grasp sorting technique. It involves swapping neighboring elements in an array until the smallest elements are sorted and appear at the top. The time complexity in the average and worst-case scenarios is O(n²).</p><p>Bubble sort on an array arr is as follows:</p><ol><li>Create an outer loop from i=0 to i = n where n is the array&#39;s length.</li><li>Create an inner loop from j=0 to n-i-1</li><li>Swap arr[j] with a[j+1] if arr[j] is less than arr[j+1]</li></ol><pre>def bubble_sort(arr):<br>  n = len(arr)<br>  for i in range(n):<br>    for j in range(0, n-i-1):<br>      if arr[j] &lt; arr[j+1]:<br>        arr[j], arr[j+1] = arr[j+1], arr[j]</pre><h4>Time and Space Complexity of Bubble Sort</h4><p>In the best case, where the array is already sorted, the time and space complexity are O(n) and O(1) respectively.</p><p>In the average case, where the array is unsorted, the time and space complexity are O(n²) and O(1).</p><p>In the worst case, where the array is sorted in reverse order, the time and space complexity are O(n²) and O(1).</p><h3>Merge Sort</h3><p>The merge sort algorithm is faster than bubble sort for large datasets. However, the trade-off is that Merge Sort uses O(n) space instead of O(1). The algorithm implements the divide-and-conquer technique by dividing an array into two sub-arrays, sorting each sub-array, and then merging the sorted sub-arrays into a final result array.</p><p>The algorithm on an array, arr is as follows:</p><ol><li>Check if the length of arr is less than two, and return arr. The array arr is sorted.</li><li>Split the array into two sides called left_arr and right_arr.</li><li>Recursively split left_arr and right_arr until their lengths are less than two.</li><li>Merge all the sub-arrays formed from steps 2 and 3.</li></ol><pre>def merge(a1,a2):<br>  res = []<br>  i = j = 0<br>  while i &lt; len(a1) and j &lt; len(a2):<br>    if a1[i] &lt; a2[j]:<br>      res.append(a1[i])<br>      i += 1<br>    else:<br>      res.append(a2[j])<br>      j += 1<br>  while i &lt; len(a1):<br>    res.append(a1[i])<br>    i += 1<br><br>  while j &lt; len(a2):<br>    res.append(a2[j])<br>    j += 1<br><br>  return res<br><br>def merge_sort(arr):<br>  if len(arr) &lt; 2:<br>    return arr<br><br>  mid = len(arr) // 2<br>  left_arr = arr[:mid]<br>  right_arr = arr[mid:]<br>  left_res = merge_sort(left_arr)<br>  right_res = merge_sort(right_arr)<br>  return merge(left_res, right_res)</pre><h4>Time and Space Complexity of Merge Sort</h4><p>The merge sort algorithm maintains a time complexity of O(nlogn) in the best, average, and worst case. The space complexity is O(n) as the sorted array grows with the input size.</p><h3>Quick Sort</h3><p>The quicksort algorithm is based on the divide and conquer technique. It uses a randomly selected pivot element to split the array into two subarrays. The first subarray contains elements that are less than the pivot and the second subarray contains elements greater than the pivot. Both subarrays are sorted recursively and then merged with the pivot to form the final sorted array.</p><p>The algorithm is as follows:</p><ol><li>Check if the array length is less than or equal to 1, and return the array.</li><li>Pick the first element of the array and set it as the pivot.</li><li>Create a left_array and fill it with values from the array that are less than the pivot.</li><li>Create a right_array and fill it with values from the array that are more than the pivot.</li><li>Call the <em>quick_sort</em> function recursively on both subarrays.</li><li>Add the results from both subarrays to the pivot and return the result.</li></ol><pre>def quick_sort(arr):<br>  if len(arr) &lt;= 1:<br>    return arr<br>  pivot = arr[0] # set pivot to first element of array <br>  left_arr = [el for el in arr (if el &lt;= pivot)]<br>  right_arr = [el for el in arr(if el &gt; pivot)]<br>  return quick_sort(left_arr) + pivot + quick_sort(right_arr)</pre><h4>Time and Space Complexity for Quick Sort</h4><p>The time complexity is O(nlogn) on average and in best cases, but O(n²) in the worst case where the pivot element is either the smallest or largest element in the array. The space complexity is O(logn).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0afcf9f892ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Programming: The Coin Change Problem.]]></title>
            <link>https://georgejuliet11.medium.com/dynamic-programming-the-coin-change-problem-6948c2712c41?source=rss-bd9ddba54cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6948c2712c41</guid>
            <dc:creator><![CDATA[Juliet George]]></dc:creator>
            <pubDate>Sun, 10 Mar 2024 22:49:58 GMT</pubDate>
            <atom:updated>2024-03-10T23:03:15.842Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to my second blog post on dynamic programming. In this post, I will demonstrate how to solve the Coin Change Problem using dynamic programming and memoization.</p><p>The problem is as follows:</p><blockquote><strong>Assuming you have an amount <em>X</em> and a list of coins,<em> lst: [c1, c2, c3, …, cn]</em>, and are asked to make change with the fewest number of coins, which coins would provide the exact change?</strong></blockquote><h3>Optimal Substructure and Recurrence:</h3><p>To achieve an optimal substructure, we select a coin c1 from a list and then determine how to change X-c1. For a given X, the recurrence can be described as follows:</p><ul><li>If X is zero, minCoin(X) would also be zero.</li><li>If X is less than zero, minCoin(X) is infinity.</li><li>If X is greater than zero, then the solution for minCoin(X) is 1 + minCoin(X-c1)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*-DAV-5wV8r1_TB2frwxsVg.png" /><figcaption>Recurrence Equation</figcaption></figure><h3>Recursion Tree</h3><p>A simple tree can be used to explain the recurrence equation above. If we have a list of coins [5, 10, 15], what combination of coins will give us exactly 20 dollars with the fewest coins?</p><ul><li>If we choose an initial value of 5, the subproblem remaining would be minCoin(15).</li><li>If we choose an initial value of 10, the subproblem remaining would be minCoin(10).</li><li>If we choose an initial value of 15, the subproblem remaining would be minCoin(5).</li></ul><p>The subproblems above make up the first level of the recursion tree. For the optimal solution, we make decisions for each subproblem until we hit a base case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*2rh5QiFUZWw2pzwXP16DDg.png" /><figcaption>Fig 2: The Recursive Tree for minCoin(20)</figcaption></figure><pre># code snippet 1:<br>def minCoin(X, coin_list):<br>  if X == 0:<br>    return 0<br>  if X &lt; 0:<br>    return 10000<br>  options = [ 1 + minCoin(X - coin, coin_list) for coin in coin_list] <br>  # for every coin we select, we call minCoin recursively <br>  # on coin_list and the difference <br>  # between X and that coin. <br>  return min(options) <br>  # we return the min number of coins needed to change X. </pre><h3>Memo Table</h3><p>Figure 2 shows the decisions and subproblems involved in solving the coin change problem for $20 and coins with denominations of $5, $10, and $15. As we follow the path, we encounter the same subproblems, such as calculating minCoin(10) and minCoin(5), multiple times. This repetition can make the recurrence equation more expensive for larger amounts and longer lists of coins.</p><p>One way to make code snippet 1 more efficient is to use a technique known as &#39;memoization&#39;. This involves storing the results of subproblems that have already been calculated in a cache. By doing this, we can avoid recalculating subproblems and make our solution more efficient. To memoize &#39;minCoin(X)&#39;, we can create a 1-D memo table called &#39;T&#39;. The table should have a length of X+1 and should be initialized with zeros.</p><pre># Code snippet 2<br>def minCoin_memo(X, coin_list):<br>  T = [0] * (X+1)<br>  for i in range(1, X+1):<br>    # loop from 1 to the X<br>    # calculate minCoin for every number within the range<br>    # save the minCoin value for every number <br>    # in the corresponding ith position in T<br>    options = [1 + T[i-coin] for coin in coin_list if(i-coin &gt;=0)]<br>    T[i] = min(options)<br>  return T(X)</pre><h3>Recover the Solution</h3><p>In code snippet 2, we can see that the function minCoin_memo(X, coin_list) returns the minimum number of coins required to change a given amount X. However, we need to modify the function to also return the specific coins used to make the change. To do this, we will create a table, S, with a length of X+1 to store the best coin options for each recursive call.</p><pre># Code snippet 3<br>def minCoin_solution(X, coin_list):<br>  T = [0] * (X+1)<br>  S = [none] * (X+1)<br>  for i in range(1, X+1):<br>    options = [(1 + T[i-coin], coin) for coin in coin_list if(i-coin &gt;=0)]<br>    T[i], S[i] = min(options)<br>  total_amount = X<br>  coins = []<br>  while total_amount &gt; 0:<br>    coins.append(S[total_amount])<br>    total_amount = total_amount - S[total_amount]<br>  return T[X], coins<br>    </pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6948c2712c41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Programming: The Rod Cutting Problem]]></title>
            <link>https://georgejuliet11.medium.com/dynamic-programming-the-rod-cutting-problem-87b7b6771976?source=rss-bd9ddba54cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/87b7b6771976</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Juliet George]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 04:19:05 GMT</pubDate>
            <atom:updated>2024-06-24T14:50:13.452Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the first blog in my dynamic programming series. In this tutorial, I will solve the Rod Cutting Problem with dynamic programming and memoization.</p><p>The problem is as follows:</p><blockquote><strong>Assuming you have a rod of length L for sale, a list of cuts, and their corresponding prices, which cuts will produce the maximum revenue?</strong></blockquote><h4>Optimal Substructure and Recurrence:</h4><p>To solve this problem with dynamic programming, it is imperative to determine the optimal substructure and write out the recurrence.</p><p>If we pick a cut with length l1 from the list of cuts, we are left with a rod of length L-l1. The final solution to the problem is derived from combining the price, p1 of the first cut with the results from solving subproblem L-l1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*ts67HEap1OON4TZ3Q3aAjQ.png" /><figcaption>fig 1: Optimal substructure</figcaption></figure><p>The next task is to define the base cases and the recurrence for the optimal value. The recurrence is also called the value function. The base cases and recurrence for this problem are as follows:</p><ul><li>If the length of the rod is zero, the max revenue is zero.</li><li>If the length is less than zero, the max revenue is -infinity.</li><li>If the length is between 1 and infinity, the max revenue is the sum of the value from the initial decision and the solution of the remaining subproblem.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*lYSMF8RA6Ts0fuv3Ql3SWw.png" /><figcaption>fig 2: Recurrence equation</figcaption></figure><blockquote>In the real world, a rod with a negative length is impossible, but since the algorithm doesn&#39;t know this, we need to handle situations where the length goes below zero.</blockquote><h4>Recursion Tree:</h4><p>Using the recurrence above, we can construct a recursion tree on a small sample size. Below is a recursion tree for maximum revenue for a rod of length 3.</p><pre>L = 3<br>sizes = [1,2]<br>prices = [0.1,0.2]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*3X4l91ckW60nVKQxIruQKg.png" /><figcaption>fig 3: Recursion Tree for the maximum revenue of a rod of length 3.</figcaption></figure><ul><li>At the root, we compute the maxRev for L = 3 by picking a length of 1 and a length of 2. The child nodes are 0.1 + maxRev(3–1) and 0.2 + maxRev(3–2).</li><li>We compute the maxRev for the child nodes and their subsequent children.</li><li>As shown on the tree, we compute maxRev(1) multiple times. When you recalculate the same values on a bigger set of data, it can cause the program to slow down. To make the program faster, we memoize already computed values.</li></ul><h4>Memo Table:</h4><p>To speed up our algorithm for maxRev, we store results from previously computed lengths and retrieve them instead of recomputing them. We achieve this by constructing a 1-dimensional memo table of length 3 to store the maxRev for each length. Let’s start by filling in the base case.</p><ul><li>The maxRev of a rod of length 0 is 0.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*nYpnL9YkYfVyqmaqlmHlWw.png" /><figcaption>fig 4: Memo table initialized with base case.</figcaption></figure><ul><li>Using the recurrence equation, we fill in the values for the remaining lengths.</li></ul><pre>T[0] = 0 #initialize the table with the base case. <br>for i in range(1,L+1):<br>  T[i] = max([T[i-sizes[j] + prices[j] for j in range(len(sizes))])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*Do2GdrhicvGiODjbNZhS6Q.png" /><figcaption>fig 4: Memo Table updated with MaxRev when the Rod length is 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*WytEcnEQCVWDo4w6C8DsvA.png" /><figcaption>fig 5: Memo Table updated with MaxRev when the Rod length is 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*X-q3_7nMQ4pB-pEAuNCEbw.png" /><figcaption>fig 6: Memo Table updated with MaxRev when the Rod length is 3</figcaption></figure><p><strong>Recover the solution</strong></p><p>To get the optimal solution, we create another table, S that stores the index of the rods that gives the max revenue for the current T[l].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*bLB6v4OT10vvT50wwoV9dA.png" /><figcaption>fig 7: The best decision for T[1] is -1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*Rozotw00e_0ZaKXf-R1H0g.png" /><figcaption>fig 7: The best decision for T[2] is 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*uMLVI9trsZyPs0WN-0ebMA.png" /><figcaption>fig 7: The best decision for T[2] is 1</figcaption></figure><p>Using the recovery table:</p><ol><li>we initial a <em>results</em> list of the rod sizes that will yield the maximum revenue</li><li>retrieve the rod length at S[L], append it to <em>results,</em></li><li>subtract the rod length from L and update L with the new value,</li><li>repeat steps 2–4 until L is zero</li><li>return <em>results</em>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*QuGrEu2eelNUmlyyYnMH5A.png" /></figure><h4>Code</h4><pre>def maxRevenue(L, sizes, prices):<br>  T = [0] * (L+1)<br>  S = [-1] * (L*1)<br>  s = len(sizes)<br>  <br>  for i in range(1, L+1):<br>    T[i], S[i] = max([(prices[j] + T[i-sizes[j]], j) for j in range(s) if i - sizes[j] &gt;=0 ])<br>    <br>  results = []<br>  l = L<br>  while l &gt; 0:<br>    if S[l] &gt;= 0:<br>      current_rod = S[l]<br>      results.append(sizes[current_rod])<br>      l = l - sizes[current_rod]<br>    else:<br>      break<br>  return T[L], results</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87b7b6771976" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Query — Build a Book Search App with React Query]]></title>
            <link>https://georgejuliet11.medium.com/react-query-build-a-book-search-app-with-react-query-74b59f5a1921?source=rss-bd9ddba54cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/74b59f5a1921</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Juliet George]]></dc:creator>
            <pubDate>Mon, 28 Aug 2023 21:45:02 GMT</pubDate>
            <atom:updated>2024-09-25T00:41:46.100Z</atom:updated>
            <content:encoded><![CDATA[<h4>React Query — Build a Book Search App with React Query</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*MTiTl2a0P5gJWfbWy7ACOQ.png" /></figure><p>In most web applications, the client communicates with the server using the browser’s fetch API or libraries such as Axios. In React applications, the traditional way to fetch and manage state is to use React Hooks e.g. <a href="https://react.dev/reference/react/useEffect">useEffect</a> and state management libraries such as <a href="https://react-redux.js.org/">Redux</a>.</p><p><strong>What is React Query?</strong></p><p>With approximately 627 contributors and 1.3m downloads a week, the React query library is becoming one of the most sought-after tools for remote state management in React applications.</p><p>The React query library is a one-stop shop for data fetching, caching, data sharing between components, offline support, pagination, and synchronization with the server state.</p><p><strong>Building a Simple Book Search Application with React Query</strong></p><p>To showcase the capabilities of the React Query library, I will code a basic book search application using the NYTimes books API.</p><p>The book search app has three components: the search form, and the results component which has the book cards. The search form comprises the input field, the button, and the form. It is used to type and submit the book name to the API. The results component renders the books returned from the API on individual cards.</p><p>Follow the steps below to create the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*-4Hcy4mUF95nG7wSca3MUw.png" /></figure><ol><li>To begin, scaffold a new react app with <a href="https://vitejs.dev/guide/">vite</a> and install dependencies:</li></ol><pre>npm create vite@latest books --template react<br>cd books &amp;&amp; npm install</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*yDqDdnHieQT1dI55lP71ew.png" /><figcaption>Setup React Project</figcaption></figure><p>2. Start up the server and delete the default code in the App.jsx.</p><pre>npm run dev</pre><pre>import &quot;./App.css&quot;;<br><br>function App() {<br>  return &lt;h1&gt;Hello World&lt;/h1&gt;;<br>}<br><br>export default App;</pre><p>3. Optional: Include CSS styles.</p><p>I used the <a href="https://styled-components.com/">Styled Components</a> 💅 framework to add personality and style to this application.</p><ul><li>To install styled-components run the following:</li></ul><pre>npm install styled-components</pre><p>4. Add a components folder in the src folder for the three main app components.</p><p>5. Create SearchForm component.</p><ul><li>Add Search.jsx to the components folder and add HTML elements with CSS styles.</li></ul><pre>import { styled } from &quot;styled-components&quot;;<br><br>const Form = styled.form`<br>  position: relative;<br>  margin-top: 30%;<br>`;<br><br>const Input = styled.input`<br>  background-color: white;<br>  border: 1px solid #160224;<br>  border-radius: 4px;<br>  height: 50px;<br>  width: 300px;<br>`;<br><br>const Button = styled.button`<br>  background-color: #9900ff;<br>  border-radius: 4px;<br>  border: 1px solid transparent;<br>  padding: 0.6em 1.2em;<br>  font-size: 1em;<br>  font-weight: 500;<br>  cursor: pointer;<br>  transition: border-color 0.25s;<br>  position: absolute;<br>  left: 200px;<br>  top: 8px;<br>  &amp;:hover {<br>    background-color: #160224;<br>  }<br>`;<br><br>export default function SearchForm() {<br>  return (<br>    &lt;Form&gt;<br>      &lt;Input /&gt;<br>      &lt;Button type=&quot;submit&quot;&gt; Search &lt;/Button&gt;<br>    &lt;/Form&gt;<br>  );<br>}</pre><ul><li>Import the SearchForm component into the App.jsx</li></ul><pre>import SearchForm from &quot;./components/Search&quot;;<br><br>function App() {<br>  return (<br>    &lt;&gt;<br>      &lt;SearchForm /&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>export default App;</pre><p>The app so far with the search form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQCrHrBlJcPE0x81q_MNpg.png" /></figure><p>6. Create the Books component to render book results from the API.</p><ul><li>Add Books.jsx to the components folder:</li></ul><pre>import { styled } from &quot;styled-components&quot;;<br><br>const Section = styled.section``;<br><br>const H1 = styled.h1``;<br><br>export default function Books() {<br>  return (<br>    &lt;Section&gt;<br>      &lt;H1&gt; Books &lt;/H1&gt;<br>    &lt;/Section&gt;<br>  );<br>}</pre><ul><li>Create an API folder in the src folder then, add config.js and api-books.js</li><li>For this exercise, I used the nytimes books API. It is free and simple to set up. Detailed setup steps here: <a href="https://developer.nytimes.com/get-started">https://developer.nytimes.com/get-started</a></li><li>Add API_KEY from the previous step to config.js</li><li>Add getBooks function to api-books.js</li></ul><pre>import { developerConfig } from &quot;./config&quot;;<br><br>export const getBooks = async () =&gt; {<br>  try {<br>    const res = await fetch(<br>      `https://api.nytimes.com/svc/books/v3/lists/overview.json?api-key=${developerConfig.API_KEY}`<br>    );<br>    return res.json();<br>  } catch (e) {<br>    console.error(e);<br>  }<br>};</pre><ul><li>[Old method] Fetch data with useEffect in the Books component.</li></ul><pre>  useEffect(() =&gt; {<br>    getBooks().then((res) =&gt; console.log(res));<br>  }, []);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*AxY2KUFNNdiLW7aSIxT73A.png" /></figure><p>7. [New method] Add React query to the app.</p><ul><li>Install react-query with the node package manager:</li></ul><pre>npm install @tanstack/react-query</pre><ul><li>Instantiate a query client with the QueryClient class inside App.jsx:</li></ul><pre>import { QueryClient } from &quot;@tanstack/react-query&quot;;<br>const queryClient = new QueryClient();</pre><ul><li>Wrap the application with the Query Client Provider.</li><li>Pass queryClient instance as value for the client property:</li></ul><pre>import SearchForm from &quot;./components/Search&quot;;<br>import Books from &quot;./components/Books&quot;;<br>import { QueryClient, QueryClientProvider } from &quot;@tanstack/react-query&quot;;<br><br>const queryClient = new QueryClient();<br><br>function App() {<br>  return (<br>    &lt;&gt;<br>      &lt;QueryClientProvider client={queryClient}&gt;<br>        &lt;SearchForm /&gt;<br>        &lt;Books /&gt;<br>      &lt;/QueryClientProvider&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>export default App;</pre><p>8. Fetch the books data with useQuery.</p><blockquote>The useQuery hook can be used to fetch data from a server with a unique identifier for the query and the async function. The unique identifier is used by the react-query library to handle refetching, caching, and resharing of query results across components.</blockquote><ul><li>import the useQuery hook to Books.jsx:</li></ul><pre>import { useQuery } from &#39;react-query&#39;</pre><ul><li>Call the useQuery hook and save the result to a variable.</li><li>[optional] Destructure the result object:</li></ul><pre>const result = useQuery([&quot;books&quot;], getBooks);<br><br>// the result can be destructured to extract specific properties<br>const { data, error, isLoading } = useQuery([&quot;books&quot;], getBooks);</pre><p><strong>data</strong>: an object with data returned from the API</p><p><strong>error</strong>: error if any</p><p><strong>isLoading</strong>: true when data is being fetched</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*IFXw0ElqNb3aGcP3nGu_Vg.png" /><figcaption>Console log of the result</figcaption></figure><p>9. Visualize the query state with the <a href="https://tanstack.com/query/v4/docs/react/devtools">React query devtools</a>.</p><p>Another benefit of using the react query is the dev-tools package. The devtools provide a way to view cached data, query objects, and data payloads. From the dev-tools UI, you can manually re-fetch data and invalidate the cache.</p><ul><li>install @tanstack/react-query-devtools:</li></ul><pre>npm install @tanstack/react-query-devtools</pre><ul><li>import devtools into App.jsx:</li></ul><pre>import { ReactQueryDevtools } from &#39;@tanstack/react-query-devtools&#39;</pre><ul><li>Add devtools to App.jsx:</li></ul><pre>import SearchForm from &quot;./components/Search&quot;;<br>import Books from &quot;./components/Books&quot;;<br>import { QueryClient, QueryClientProvider } from &quot;react-query&quot;;<br>import { ReactQueryDevtools } from &#39;@tanstack/react-query-devtools&#39;<br><br>const queryClient = new QueryClient();<br><br>function App() {<br>  return (<br>    &lt;QueryClientProvider client={queryClient}&gt;<br>      &lt;ReactQueryDevtools /&gt;<br>      &lt;SearchForm /&gt;<br>      &lt;Books /&gt;<br>    &lt;/QueryClientProvider&gt;<br>  );<br>}<br><br>export default App;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*0ABrwn-mG7PFDxl4_mtWWg.png" /><figcaption>Devtools on the page</figcaption></figure><p>10. Show Books on the UI</p><ul><li>Create BookCard.jsx and add book props:</li></ul><pre>import { styled } from &quot;styled-components&quot;;<br><br>const Card = styled.div`<br>  border: 1px solid transparent;<br>  border-radius: 8px;<br>`;<br><br>const Link = styled.a`<br>  display: inline-flex;<br>  justify-content: center;<br>  padding: 8px 8px;<br>  text-align: center;<br>  font-weight: 500;<br>  background-color: #9900ff;<br>  border-radius: 8px;<br>  cursor: pointer;<br>  text-decoration: none;<br>  color: white;<br>  &amp;:hover {<br>    background-color: #160224;<br>  }<br>`;<br><br>const Image = styled.img`<br>  width: 100%;<br>  height: 50%;<br>  object-fit: cover;<br>  border-radius: 8px;<br>`;<br><br>const StyledDiv = styled.div`<br>  padding: 4px;<br>`;<br><br>const H5 = styled.h5`<br>  font-size: 24px;<br>  font-weight: 700;<br>`;<br><br>const P = styled.p`<br>  font-weight: 500;<br>  margin-bottom: 20px;<br>  height: 110px;<br>`;<br><br>export default function BookCard({ book }) {<br>  return (<br>    &lt;&gt;<br>      &lt;Card&gt;<br>        &lt;Image src={book.book_image} /&gt;<br>        &lt;StyledDiv&gt;<br>          &lt;H5&gt; {book.title} &lt;/H5&gt;<br>          &lt;P&gt; {book.description} &lt;/P&gt;<br>          &lt;Link target=&quot;_blank&quot; href={book.amazon_product_url}&gt;<br>            View on Amazon<br>          &lt;/Link&gt;<br>        &lt;/StyledDiv&gt;<br>      &lt;/Card&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><ul><li>import BookCard component into Books component</li><li>Pass the fetched data as props to the BookCard</li></ul><pre>import { styled } from &quot;styled-components&quot;;<br>import { getBooks } from &quot;../api/api-books&quot;;<br>import { useQuery } from &quot;@tanstack/react-query&quot;;<br>import BookCard from &quot;./BookCard&quot;;<br><br>const Section = styled.section`<br>  display: grid;<br>  grid-template-columns: repeat(3, 1fr);<br>  margin: 100px 100px;<br>  gap: 40px;<br>`;<br><br>const H1 = styled.h1`<br>  margin-left: 100px;<br>  font-size: 35px;<br>`;<br><br>export default function Books() {<br>  const { data, isLoading } = useQuery([&quot;books&quot;], getBooks);<br><br>  return (<br>    &lt;&gt;<br>      &lt;H1&gt; Best Sellers List &lt;/H1&gt;<br>      &lt;Section&gt;<br>        {isLoading ? (<br>          &lt;p&gt;Loading ...&lt;/p&gt;<br>        ) : (<br>          &lt;&gt;<br>            {data.results.lists[0].books.map((book) =&gt; (<br>              &lt;BookCard book={book} /&gt;<br>            ))}<br>          &lt;/&gt;<br>        )}<br>      &lt;/Section&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uAOAX4XG-P8l-BKZJKjcbQ.png" /><figcaption>Books on the UI</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74b59f5a1921" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Root of the Binary Search Tree.]]></title>
            <link>https://georgejuliet11.medium.com/the-root-of-the-binary-search-tree-428cbd29887c?source=rss-bd9ddba54cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/428cbd29887c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[binary-search-tree]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Juliet George]]></dc:creator>
            <pubDate>Wed, 06 May 2020 06:27:57 GMT</pubDate>
            <atom:updated>2021-02-02T15:13:26.459Z</atom:updated>
            <content:encoded><![CDATA[<h3>Binary Search Tree.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/0*GPERnou_J9E2c9-B.jpg" /><figcaption>Doubts never end. If one doubt is removed, another takes its place. It is like removing the leaves of a tree one by one. Even if all the leaves are clipped off, new ones grow. The tree itself must be uprooted. <a href="https://www.brainyquote.com/authors/ramana-maharshi-quotes"><strong>Ramana Maharshi</strong></a></figcaption></figure><p>A Binary Search Tree(BST) is a data structure in which each node can have a maximum of two children. In a BST, for each node, n, the child to the left, n.left is less than or equal to n and the child to the right, n.right is greater than or equal to n. That is, if data y, is stored in n, y is greater than all values stored in the nodes in the left subtree and less than values in nodes in the right subtree. The topmost node is called the root and the nodes without children are called leaf nodes. On average the runtime complexity for BST operation is O(n), where n is the longest path through the tree or the height of the tree. Let’s take a look at how the different BST operations work.</p><p>Inserting into a BST has the worst-case scenario runtime of O(n), where n is the height of the tree. The best-case scenario O(log(n)) can be found when you are inserting into a Perfect Binary Tree. This is because if a tree with n nodes is kept balanced, it’s height is log(n), which leads to a lookup operation of O(log(n)). The Perfect Binary Tree has 2^(n+1) — 1 number of nodes, that is, if the height of the tree is 2, then it has 7 nodes. See the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*QJFCZk8CkGDQMi4jfHpmbQ.png" /><figcaption>A Perfect Binary Tree with n = 2.</figcaption></figure><p>To insert an element into BST, start by examining the root. if the element is less than the root, insert it into the left subtree. If the element is greater than the root, then insert it into the right subtree. See the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*1IqauXfSPbObBQ5GQMo9kA.png" /><figcaption>Insert element less than the value in the root.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*SyrdtvmNShWKwKcVLcwfEA.png" /><figcaption>Insert element greater than the value in the root.</figcaption></figure><p>Let’s find an item in the BST. The ordered state of the BST allows for efficient navigation of the tree to search for an element. The time complexity is O(n) for the worst-case in a search operation, and every recursive call descends one level in the tree until it goes from the root to the leaf.</p><p>To find an element in the BST, we arrive at a given node and compare the element to the data stored in that node. If it is equal, we have found the location. If not, we check if it is greater or less than, if greater, the element can be found on the right subtree. If less than, the element can be found on the left subtree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*cLopWVP6ZmQOG_ZwOrn_iA.png" /><figcaption>Searching for a value less than the root value.</figcaption></figure><p>The time complexity of the delete operation is O(n). There are various ways to delete from the BST and it depends on what you want to remove.</p><p>To remove the minimum value in the tree, go through the leftmost subtrees until you find the node. To find the maximum, go to the rightmost subtree and delete it.</p><p>If the node to be deleted has one child, delete the node and replace it with the child. If the node has two child nodes, simply, use T. Hibbard’s method of deleting the node by replacing it with the successor. This is the more complex case and it might be helpful to list the process in steps:</p><p>Step 1: Point to the node to be deleted, call the pointer D.</p><p>Step 2: Point to the minimum element from the right tree (the right tree from the element we need to delete), call the pointer R.</p><p>Step 3: Move R to the position of D and delete D.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*PyVuHzEJ5c85vJOs3Bk62Q.png" /><figcaption>Deleting a node with 2 child nodes.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*0EMYEETRlRexDA1JJdGm-A.png" /><figcaption>The node has been deleted.</figcaption></figure><p>I hope that this introduction to Binary Search Tree was useful and has at least given you an understanding of its different operations. Please leave questions and feedback in the comment section below. See you in my next blog post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=428cbd29887c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>